<?php

namespace App\Models\Tools;

use Illuminate\Support\Facades\Log;
use OSS\Core\OssException;
use OSS\OssClient;

/**
 * 工具类：将来飞网公众号前端资源发布到oss
 * Class LaifeiPublish
 * @package App\Models\Tools
 */
class LaifeiPublish
{
    private $ossClient;
    private $bucket;
    public $files;
    public $url;

    /**
     * LaifeiPublish constructor.
     */
    public function __construct()
    {
        try {
            // 新建一个oss实例
            $accessKeyId = env('OSS_LF_ACCESS_KEY_ID');
            $accessKeySecret = env('OSS_LF_ACCESS_KEY_SECRET');
            $endpoint = env('OSS_LF_END_POINT');
            $this->ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $this->bucket = env('OSS_LF_BUCKET');
            $this->url = env('OSS_LF_URL');
        } catch (OssException $e) {
            Log::error(LaifeiPublish::class, ['errMsg' => $e->getMessage()]);
        }
    }

    /**
     * 删除文件
     * @return bool
     */
    public function removeFiles()
    {
        // 根目录下包含首页的index.html和favicon.ico
        try{
            $this->ossClient->deleteObject($this->bucket, 'index.html');
            $this->ossClient->deleteObject($this->bucket, 'favicon.ico');
        } catch (OssException $e) {
            Log::error(LaifeiPublish::class, ['errMsg' => $e->getMessage()]);
            return false;
        }


        // 默认需要修改的文件夹有css、img、js
        $dir = ['css','img','js'];
        // 查询所有文件
        foreach ($dir as $value) {
            $prefix = $value.'/';
            $delimiter = '/';
            $nextMarker = '';
            $maxkeys = 1000;
            $options = array(
                'delimiter' => $delimiter,
                'prefix' => $prefix,
                'max-keys' => $maxkeys,
                'marker' => $nextMarker,
            );
            try {
                $listObjectInfo = $this->ossClient->listObjects($this->bucket, $options);
                $objectList = $listObjectInfo->getObjectList(); // object list
                if (!empty($objectList)) {
                    $files = [];
                    foreach ($objectList as $objectInfo) {
                        $file_name = $objectInfo->getKey();
//                        if ($file_name !== $prefix) {
                            // 记录到数组
                            $files[] = $file_name;
//                        }
                    }
                    // 删除原文件
                    $this->ossClient->deleteObjects($this->bucket, $files);
                }
            } catch (OssException $e) {
                Log::error(LaifeiPublish::class, ['errMsg' => $e->getMessage()]);
                return false;
            }
        }
        return true;
    }


    /**
     * 上传文件到文件夹
     * @param null $bar
     * @return bool
     */
    public function uploadFiles($bar = null)
    {
        try {
            $time = date('Y-m-d H:i:s');
            $count = count($this->files);
            foreach ($this->files as $key => $file) {
                $object = substr($file, strlen($this->url)+1);
                $percent = floor($key*100/$count);
                if($bar){
                    $bar->advance();
                } else {
                    echo "\n($percent%)正在上传$object...";
                }
                $this->ossClient->uploadFile($this->bucket, "history/$time/$object", $file);
                $this->ossClient->uploadFile($this->bucket, $object, $file);
            }
        } catch (OssException $e) {
            Log::error(LaifeiPublish::class, ['errMsg' => $e->getMessage()]);
            return false;
        }
        return true;
    }

    /**
     * 遍历文件夹所有的文件名，保存到$files
     * @param $dir
     */
    public function list_file($dir){
        // 读取文件夹
        $temp=scandir($dir);
        // 遍历文件夹
        foreach($temp as $v){
            $a=$dir.'/'.$v;
            if(is_dir($a)){//如果是文件夹则执行
                if($v=='.' || $v=='..'){//判断是否为系统隐藏的文件.和..  如果是则跳过否则就继续往下走，防止无限循环再这里。
                    continue;
                }
                $this->list_file($a);//因为是文件夹所以再次调用自己这个函数，把这个文件夹下的文件遍历出来
            }else{
                $this->files[] = $a;
            }
        }
    }

}
